package com.changli02.tcpudp.chat;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class chatServerTest {

    //online 集合用来存储 客户端
    static ArrayList<Socket> online = new ArrayList<>();

    public static void main(String[] args) {

        try {
            //创建服务端
            ServerSocket serverSocket = new ServerSocket(8989);
            //有客户端则将其添加到客户端

            while (true){
                //接收客户端
                Socket socket = serverSocket.accept();
                //添加至online
                online.add(socket);

                //另外一个线程
                //主要负责获取当前socket中的数据，并分发给当前聊天室的所有的客户端
                HandlerMessage hm = new HandlerMessage(socket);
                hm.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}

class HandlerMessage extends Thread{
    private Socket socket;
    private String ip;

    public HandlerMessage(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            ip = socket.getInetAddress().getHostAddress();
            //给其他 客户说明，我上线了
            SendToOther(ip+"上线了");
//          接收客户端发送的消息
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            String str;
            while ((str = br.readLine())!=null){
                SendToOther(ip+":"+str);

            }
            SendToOther(ip+"下线了");
        } catch (IOException e) {
            try {
                SendToOther(ip +"掉线了");
            } catch (Exception ex) {
                e.printStackTrace();
            }
        } finally {
            chatServerTest.online.remove(socket);
        }


    }
    //封装一个方法 给其他客户端发送消息
    public void SendToOther(String str) throws  IOException{
        for (Socket on: chatServerTest.online){
            OutputStream os = on.getOutputStream();
            PrintStream ps = new PrintStream(os);
            ps.println(str);
        }
    }
}
